package com.tool.app.common;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Collections;
import java.util.List;

/**
 * 分页数据封装类
 * Created by ls on 2019/4/19.
 */
@Data
public class CommonPage<T> {
    private Integer pageNum;
    private Integer pageSize;
    private Integer totalPage;
    private Long total;
    private List<T> list;

    /**
     * 将MyBatis Plus 分页结果转化为通用结果
     */
    public static <T> CommonPage<T> restPage(Page<T> pageResult) {
        CommonPage<T> result = new CommonPage<>();
        result.setPageNum(Convert.toInt(pageResult.getCurrent()));
        result.setPageSize(Convert.toInt(pageResult.getSize()));
        result.setTotal(pageResult.getTotal());
        result.setTotalPage(Convert.toInt(Math.ceil((double)pageResult.getTotal()/(double) pageResult.getSize())));
        result.setList(pageResult.getRecords());
        return result;
    }

    public static <T> CommonPage<T> restPage(List<T> list,Integer pageNo,Integer pageSize, Long total,Integer pages) {
        CommonPage<T> result = new CommonPage<>();
        result.setPageNum(pageNo);
        result.setPageSize(pageSize);
        result.setTotal(total);
        result.setTotalPage(pages);
        result.setList(list);
        return result;
    }

    public static <T> CommonPage<T> empty() {
        CommonPage<T> result = new CommonPage<>();
        result.setPageNum(1);
        result.setPageSize(0);
        result.setTotal(0L);
        result.setTotalPage(0);
        result.setList(Collections.emptyList());
        return result;
    }

    public static <T> CommonPage<T> restPageClass(List<T> list, Page classPage) {
        CommonPage<T> result = new CommonPage<>();
        result.setPageNum(Convert.toInt(classPage.getCurrent()));
        result.setPageSize(Convert.toInt(classPage.getSize()));
        result.setTotal(classPage.getTotal());
        result.setTotalPage(Integer.parseInt(classPage.getPages()+""));
        result.setList(list);
        return result;
    }

}
